from PyQt5.QtWidgets import QDialog, QVBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox
from PyQt5.QtCore import Qt
import os
import json

class AlertDialog(QDialog):
    def __init__(self):
        super(AlertDialog, self).__init__()
        # 字段字典
        self.field_dict = {}
        self.initUI()

    def initUI(self):
        # 设置窗口标题
        self.setWindowTitle("报警邮件配置")
        # 设置窗口大小
        self.resize(300, 270)

        form_data_list = [
            {"title":"SMTP服务器:", "field":"smtp"},
            {"title":"发件箱:", "field":"from"},
            {"title":"密码:", "field":"pwd"},
            {"title":"收件人(多个用逗号分隔):", "field":"to"},
        ]

        # 读取文件中的配置
        # 判断文件是否存在
        old_data_dict = {}
        file_path = os.path.join("db", "alart.json")
        if os.path.exists(file_path):
            file_obj = open((file_path), mode="r", encoding="utf-8")
            # 读取文件中的数据
            old_data_dict = json.load(file_obj)
            file_obj.close()

        layout = QVBoxLayout()

        for item in form_data_list:
            lbl = QLabel()
            lbl.setText(item['title'])
            layout.addWidget(lbl)

            txt = QLineEdit()
            layout.addWidget(txt)

            # smtp, from, pwd, to
            field = item['field']
            # 将读取到的值赋值给界面
            if old_data_dict and field in old_data_dict:
                txt.setText(old_data_dict[field])

            # 字段字典保存字段名和组件
            self.field_dict[item['field']] = txt

        btn_save = QPushButton("保存")
        btn_save.clicked.connect(self.event_click_save)
        layout.addWidget(btn_save, 0, Qt.AlignRight)

        self.setLayout(layout)

    def event_click_save(self):
        # 保存信息
        # print('save smtp')
        # 数据字典-保存界面输入的数据
        data_dict = {}

        # 获取界面数据保存到数据字典中
        for key, field in self.field_dict.items():
            value = field.text().strip()
            if not value:
                QMessageBox.warning(self, "错误", "SMTP配置项不能为空")
                return
            data_dict[key] = value
        
        # print(data_dict)
        # 保存到文件
        file_obj = open(os.path.join("db", "alart.json"), mode="w", encoding="utf-8")
        # 保存到文件
        json.dump(data_dict, file_obj)
        # 文件关闭
        file_obj.close()

        # 关闭对话框
        self.close()
